import { Injectable, bind } from 'angular2/core';
import { BehaviorSubject } from 'rxjs/subject/BehaviorSubject';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable'
import { Subject } from 'rxjs/Subject';
import { TreeData } from './tree-data';

@Injectable()
export class TreeViewService {
  currentSelection = new BehaviorSubject<number>(null);
  treeData: BehaviorSubject<TreeData> = new BehaviorSubject<TreeData>(null);

  public changeSelection(id: number) {
    if (this.currentSelection.getValue() !== id) {
      this.currentSelection.next(id);
    }
  }

  public foldToggle(id: number) {
    let tree = this.treeData.getValue();
    let node = tree.findNodeById(id);
    if (node) {
      node.expand = !node.expand;
    }
    this.treeData.next(tree);
  }

  public foldForId(id: number): Observable<boolean> {
    return this.treeData.map(tree => {
      let node = tree.findNodeById(id);
      if (node) {
        return node.expand;
      } else {
        return false;
      }
    });
  }
}

export var treeviewServiceInjectables: Array<any> = [
  bind(TreeViewService).toClass(TreeViewService)
];
